<script setup lang="ts">
import * as THREE from 'three';
import {nextTick, onMounted} from "vue";
import {MMDLoader} from "three/addons/loaders/MMDLoader.js";
import {OrbitControls} from "three/addons/controls/OrbitControls.js";

const init = () => {
  const dom:HTMLDivElement = document.querySelector('.ddd') || document.createElement('div',{
    class: 'ddd'
  })
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera( 55, dom?.offsetWidth / dom?.offsetHeight, 0.1, 2000 );
  camera.position.z = 30
  // camera.position.y = 50
  // camera.lookAt(0,10,0)

  const controls = new OrbitControls( camera ,dom)
  controls.autoRotate = true
  controls.enableDamping = true;  // 启用电阻尼，使移动更平滑
  controls.dampingFactor = 0.05;
  controls.screenSpacePanning = false;
  controls.minDistance = 5;
  controls.maxDistance = 50;
  controls.target.set(0, 0, 0);  // 初始目标位置

  controls.update();

  const renderer = new THREE.WebGLRenderer({
    alpha:true
  });

  renderer.setSize( dom?.offsetWidth, dom?.offsetHeight );
  dom?.appendChild( renderer.domElement );

  const directionalLight1 = new THREE.DirectionalLight(0xffffff, 1.5);
  directionalLight1.position.set(-300,-300,600)
  scene.add(directionalLight1);
  const directionalLight2 = new THREE.DirectionalLight(0xffffff, 1.5);
  directionalLight2.position.set(600,200,600)
  scene.add(directionalLight2);

  const loader = new MMDLoader()

  // Load a MMD model
  loader.load(
      // path to PMD/PMX file
      '/by/薄荷.pmx',
      // called when the resource is loaded
      function ( mesh ) {

        mesh.position.y = -13
        // camera.lookAt(mesh.position)
        scene.add( mesh );

      },
      // called when loading is in progresses
      function ( xhr ) {

        console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );

      },
      // called when loading has errors
      function ( error ) {
        console.log( 'An error happened' );

      }
  );

  function animate() {
    requestAnimationFrame( animate );
    controls.update();
    renderer.render( scene, camera );
  }
  animate();
}

onMounted(async ()=>{
  await nextTick()
  init()
})

</script>

<template>
<div class="ddd">
</div>
</template>

<style scoped lang="scss">
.ddd{
  width: 100%;
  height: 100%;
}
</style>
